<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :width="600">
    <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px" @keyup.enter="submitHandle()">
      <el-form-item label="一级标签" prop="parentId">
        <el-select v-model="dataForm.parentId" placeholder="请选择一级标签（不选，则此标签为一级标签）">
          <el-option v-for="item in props.firstTag" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="标签名" prop="name">
        <el-input v-model="dataForm.name" placeholder="请输入标签名" />
      </el-form-item>
      <el-form-item label="标签描述" prop="description">
        <el-input v-model="dataForm.description" placeholder="请输入标签描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue'

import { ListVO, SubmitDTO } from '../data.d'
import type { FormRules, FormInstance } from 'element-plus'

import { add, update } from '../service'

const props = defineProps<{
  firstTag: ListVO[]
}>()
const emit = defineEmits<{
  (e: 'refreshDataList'): void
}>()

const visible = ref(false)
const dataFormRef = ref<FormInstance>()

const dataForm = reactive<SubmitDTO>({
  id: undefined,
  description: '',
  name: '',
  parentId: undefined,
})

const init = async (row?: ListVO) => {
  visible.value = true
  await nextTick()
  dataForm.id = undefined

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields()
  }

  if (row) {
    Object.assign(dataForm, row)
  }
}

const dataRules = reactive<FormRules<typeof dataForm>>({
  name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
})

// 表单提交
const submitHandle = () => {
  dataFormRef.value!.validate(async (valid) => {
    if (!valid) return

    const res = dataForm.id ? await update(dataForm) : await add(dataForm)
    if (res) {
      visible.value = false
      emit('refreshDataList')
    }
  })
}

defineExpose({
  init,
})
</script>
